import { Button, Modal, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';

import $utils from '@/utils/utils';
import { appTypeData, platformNames } from '@/utils/common';
import moment from 'moment';
import { appConfigureDelete, getAppConfigureList } from '@/services/appConfigure';

const initDate = {};

const AppConfigureList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);


    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = l_state ? {
                ...l_state,
            } : { ...initDate, };
            setParams(data);
        }
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        const data = {
            ...initDate,
        }
        if (JSON.stringify(initParams) === JSON.stringify(data)) {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    // 删除弹窗
    const confirm = (id: number) => {
        Modal.confirm({
            title: '删除',
            content: '确定是否要删除',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 删除通知
                const msg = await appConfigureDelete({ id });
                if (msg.code === 0) {
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    const columns: ProColumns<any>[] = [
        {
            title: '版本标题',
            dataIndex: 'versionTitle',
            width: 120,
        },
        {
            title: '版本名称',
            search: false,
            dataIndex: 'versionName',
            width: 130,
        },
        {
            title: '版本号',
            search: false,
            dataIndex: 'versionCode',
        },
        {
            title: '类型',
            dataIndex: 'appType',
            valueType: 'select',
            width: 150,
            fieldProps: {
                options: appTypeData
            },
        },
        {
            title: '下载地址',
            search: false,
            dataIndex: 'url',
            render: (dom: any, record: any) => {
                return (<div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>{dom}</div>)
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            search: false,
            hideInForm: true,
            width: 120,
            fieldProps: {
                textWrap: 'word-break',
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Access accessible={true}>
                        <Button type="primary" size="small" onClick={() => {
                            const newTab = {
                                name: `查看${record.versionName}`,
                                path: '/System/appConfigure/detail',
                                state: {
                                    status: 'detail',
                                    data: record
                                },
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab);

                            history.push({
                                pathname: '/System/appConfigure/detail',
                                state: {
                                    status: 'detail',
                                    data: record
                                }
                            });
                        }}>详情</Button>
                    </Access>
                    <Access accessible={true}>
                        <Button type="primary" size="small" danger onClick={() => {
                            confirm(record.id)
                        }}>删除</Button>
                    </Access>
                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                form={{
                    initialValues: initParams
                }}
                formRef={formRef}
                search={access.can_numAll.search ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 8,
                    },
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                const data = {
                                    ...initDate,
                                };
                                setParams(data);
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                options={false}
                title={() => [
                    <Access key="index" accessible={access.can_numAll.create}>
                        <Button type="primary" onClick={() => {
                            const newTab = {
                                name: `添加版本升级配置`,
                                path: '/System/appConfigure/detail',
                                state: {
                                    status: 'create'
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/System/appConfigure/detail',
                                state: {
                                    status: 'create'
                                }
                            });
                        }}>添加</Button>
                    </Access>

                ]}
                request={async (params: any) => {
                    const msg = await getAppConfigureList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: '版本升级配置',
                            path: '/System/appConfigure',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.list || [],
                        success: msg.code === 0,
                        total: msg.body?.count,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default AppConfigureList;
